package com.project.common.caching.redis;

import com.project.common.caching.provider.CacheProvider;
import com.project.common.caching.provider.HashProvider;
import com.project.common.caching.provider.ValueProvider;
import lombok.Synchronized;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisCacheProvider implements CacheProvider {

    private final RedisTemplate<String, String> redisTemplate;
    private final RedisValueProvider redisValueProvider;
    private final RedisHashProvider redisHashProvider;

    public RedisCacheProvider(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.redisValueProvider = new RedisValueProvider(redisTemplate);
        this.redisHashProvider = new RedisHashProvider(redisTemplate);
    }

    @Override
    public ValueProvider forValue() {
        return redisValueProvider;
    }

    @Override
    public HashProvider forHash() {
        return redisHashProvider;
    }

    @Override
    public boolean exists(String key) {
        Boolean exists = redisTemplate.hasKey(key);
        return exists != null && exists;
    }

    @Override
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void expire(String key, long expiration, TimeUnit timeUnit) {
        redisTemplate.expire(key, expiration, timeUnit);
    }

    @Override
    public void persist(String key) {
        redisTemplate.persist(key);
    }

    @Override
    public long ttl(String key) {
        Long ttl = redisTemplate.getExpire(key);
        if (ttl == null) {
            return 0;
        }
        return ttl;
    }

    @Override
    public void publish(String topic, String message) {
        redisTemplate.convertAndSend(topic, message);
    }

    @Override
    @Synchronized
    public boolean setIfAbsent(String key, String value) {
        return redisTemplate.opsForValue().setIfAbsent(key, value);
    }
}
